const Koa = require("koa");
const Router = require("@koa/router");
const cors = require("koa2-cors");
const { koaBody } = require("koa-body");
const fs = require("fs");
const path = require("path");

// 创建日志目录
const logDir = path.join(__dirname, '../logs');
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

// 全局错误日志
function logError(message) {
  const timestamp = new Date().toISOString();
  const logMessage = `[${timestamp}] ${message}\n`;
  fs.appendFileSync(path.join(logDir, 'app-error.log'), logMessage);
  console.error(`[${new Date().toLocaleString()}] ${message}`);
}

// 处理未捕获的异常
process.on('uncaughtException', (err) => {
  logError(`未捕获的异常: ${err.message}`);
  logError(`错误堆栈: ${err.stack}`);
});

process.on('unhandledRejection', (reason, promise) => {
  logError(`未处理的Promise拒绝: ${reason}`);
});

const app = new Koa();
const router = new Router();
const type0Router = require("./type0");

// 初始化队列
require('./queues/excelQueue');

app.use(koaBody());

app.use(
  cors({
    origin: "*", // 允许所有域名跨域
    credentials: true, // 允许跨域的时候带着 cookie
  })
);

// 错误处理中间件
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    logError(`请求处理错误: ${err.message}`);
    logError(`错误堆栈: ${err.stack}`);
    ctx.status = err.status || 500;
    ctx.body = { success: false, message: err.message };
  }
});

router.get("/test", async (ctx) => {
  ctx.body = { success: true, message: "你好" };
});

app.use(router.routes()).use(router.allowedMethods());
app.use(type0Router.routes()).use(type0Router.allowedMethods());

app.listen(3000, '0.0.0.0');
console.log(`[${new Date().toLocaleString()}] 服务器已启动，监听端口: 3000`);
